package com.betty.visitprovider;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ContentResolver resolver;
    private static final String uri = "content://betty/person";
    private ListView lv;
    private ArrayList<HashMap<String,String>> list;
//    private SimpleAdapter adapter;
    private SimpleCursorAdapter adapter;//第一种方法通过 SimpleCursorAdapter中的cursor作为数组
    private  Cursor cursor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        resolver = getContentResolver();
        lv=(ListView)findViewById(R.id.lv_show);
      adapter=new SimpleCursorAdapter(this,R.layout.list_item,null,new String[]{"name","age"},new int[]{R.id.tv_name,R.id.tv_age});
//        adapter = new SimpleAdapter(this,list,android.R.layout.simple_list_item_2,new String[]{"name","age"},new int[]{R.id.tv_name,R.id.tv_age});
        lv.setAdapter(adapter);
    }
    public void insert(View view){
        ContentValues values = new ContentValues();
        values.put("name","张三");
        values.put("age","18");
        Uri insert = resolver.insert(Uri.parse(uri),values);
        Long parseID = ContentUris.parseId(insert);
        if (parseID>0)
            Toast.makeText(this, "添加数据成功", Toast.LENGTH_SHORT).show();
    }
    public void query(View view){
        cursor = resolver.query(Uri.parse(uri),null,null,null,null);
        adapter.swapCursor(cursor);
//        if (cursor.moveToFirst()){
//            while (cursor.moveToNext()){
//                HashMap<String,String> map = new HashMap<String, String>();
//                String name=cursor.getString(cursor.getColumnIndex("name"));
//                String age=cursor.getString(cursor.getColumnIndex("age"));
//                map.put("name",name);
//                map.put("age",age);
//                list.add(map);
//            Log.i("TAG","*********name*********"+name);
//            Log.i("TAG","**********age**********"+age);
            }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        while (cursor!=null)
            cursor.close();
    }
}
